import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './dto/user.entity';
import { CommonResult, typeResult } from '../utils/result';
import { v4 } from 'uuid';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private jwtService: JwtService,
  ) {}

  async findUser(username): Promise<typeResult<User>> {
    const user = await this.userRepository.findOne({
      select: [
        'username',
        'email',
        'password',
        'state',
        'id',
        'alias',
        'avatar',
        'level',
        'countLevel',
      ],
      where: { username },
    });

    return CommonResult<User>(user, true, 200, '查询成果');
  }

  async findUserByEmails(username: string, user: any): Promise<any> {
    if (user.id === '22') {
      const emails = await this.userRepository.find({
        select: ['email', 'username'],
      });
      return emails;
    }

    const emails = await this.userRepository.find({
      select: ['email'],
      where: { username },
    });
    return emails;
  }

  async userLogin(user: User): Promise<typeResult<any>> {
    // 登录逻辑
    const result = await this.userRepository.findOne({
      select: [
        'id',
        'username',
        'email',
        'password',
        'alias',
        'avatar',
        'level',
        'countLevel',
        'createTime',
      ],
      where: {
        username: user.username,
      },
    });
    if (!result) {
      return CommonResult(null, false, 400, '用户名或密码错误');
    }
    const resultToken = await this.jwtService.signAsync({
      username: user.username,
      password: user.password,
      id: result.id,
      level: result.level,
      countLevel: result.countLevel,
    });
    const data = {
      username: result.username,
      email: result.email,
      token: resultToken,
      alias: result.alias,
      avatar: result.avatar,
      level: result.level,
      countLevel: result.countLevel,
      createTime: result.createTime,
    };
    // this.userRepository.update(result.id as never, {
    //   state: '1',
    // });
    return CommonResult(data, true, 200, '登录成功');
  }

  async createUser(body: User): Promise<typeResult<User>> {
    try {
      const uuid = BigInt(`0x${v4().replace(/-/g, '')}`)
        .toString()
        .slice(0, 16);
      const user = new User();
      user.id = uuid as never;
      user.username = body.username;
      user.password = body.password;
      user.email = body.email;
      user.level = 1000;
      user.countLevel = 0;
      user.alias = '邻居';
      await this.userRepository.save(user);
      return CommonResult<User>(user).success(user, '注册成功');
    } catch (error) {
      return CommonResult<User>().error('注册失败');
    }
  }

  setUserState(id: any, state: string): Promise<any> {
    return this.userRepository.update(id, {
      state,
    });
  }

  async setUSerAvatar(url: string, id: any) {
    return await this.userRepository.update(id, {
      avatar: url,
    });
  }

  async setCountLevel(username: string, level: number) {
    const user = await this.findUser(username);
    if (user.data == null) return;
    let overflowCount = 0;
    // 浏览文章 100 点赞加10 评论加50
    let currentCountLevel = user.data.countLevel;
    if (level === 30) {
      //  浏览文章 进度加 10
      currentCountLevel += 3;
    } else if (level === 50) {
      //  发布文章 进度加 5
      currentCountLevel += 5;
    } else if (level === 80) {
      //  评论 进度加  8
      currentCountLevel += 8;
    }
    this.userRepository.update(user.data.id as never, {
      level: Number(user.data.level) + level,
    });
    if (user.data.countLevel >= 100) {
      overflowCount = user.data.countLevel - 100; //溢出值
      return await this.userRepository.update(user.data.id as never, {
        countLevel: overflowCount,
      });
    } else {
      return await this.userRepository.update(user.data.id as never, {
        countLevel: currentCountLevel,
      });
    }
  }
}
